package com.pz.cloud.framework.student.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pz.cloud.framework.base.model.Pageable;
import com.pz.cloud.framework.business.pzStudent.entity.PzStudent;
import com.pz.cloud.framework.business.pzStudent.service.IPzStudentService;
import com.pz.cloud.framework.business.student.entity.Student;
import com.pz.cloud.framework.business.student.service.IStudentService;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
public class PullStudentJob implements Job {

    @Autowired
    private IPzStudentService pzStudentService;

    @Autowired
    private IStudentService studentService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ISysDictService sysDictService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(" --- 拉取学生信息调度开始 --- ");
        PzStudent entity = new PzStudent();
        int size = 1000;
        int count = pzStudentService.count();
        int step = 1;

        LambdaQueryWrapper<SysRole> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysRole::getRoleName, "学生");
        SysRole role = sysRoleService.getOne(wrapper, false);

        List<DictModel> politicalDict = sysDictService.queryDictItemsByCode("political_outlook");
        Map<String, String> politicalMap = politicalDict.stream().collect(Collectors.toMap(DictModel::getText, DictModel::getValue));

        while (count > 0) {
            int current = count > size ? size : count;
            Pageable pageable = new Pageable();
            pageable.setPageNo(step++);
            pageable.setPageSize(current);
            List<PzStudent> list = pzStudentService.findPage(entity, pageable);
            list.forEach(r -> {
                SysUser sysUser = sysUserService.getUserByName(r.getXH());
                if (sysUser == null) {
                    sysUser = new SysUser();
                    sysUser.setUsername(r.getXH());
                    sysUser.setRealname(r.getXM());
                    sysUser.setDelFlag(0);
                    sysUser.setSex(Integer.parseInt(r.getXBM()));
                    sysUser.setPhone(r.getFILED4());
                    sysUser.setWorkNo(r.getXH());
                    boolean save = sysUserService.save(sysUser);
                    if (save) {
                        log.info("用户入库完成：{}", r.getXH());
                        if (role != null) {
                            String roleId = role.getId();
                            LambdaQueryWrapper<SysUserRole> urWrapper = Wrappers.lambdaQuery();
                            urWrapper.eq(SysUserRole::getUserId, sysUser.getId()).eq(SysUserRole::getRoleId, roleId);
                            SysUserRole one = sysUserRoleService.getOne(urWrapper, false);
                            if (one == null) {
                                SysUserRole sysUserRole = new SysUserRole();
                                sysUserRole.setRoleId(roleId);
                                sysUserRole.setUserId(sysUser.getId());
                                if (sysUserRoleService.save(sysUserRole)) {
                                    log.info("用户角色入库完成：{}", r.getXH());
                                }
                                else {
                                    log.info("用户角色入库失败：{}", r.getXH());
                                }
                            }
                        }
                    }
                    else {
                        log.info("用户入库失败：{}", r.getXH());
                    }
                }
                else if (!Objects.equals(sysUser.getRealname(), r.getXM()) ||
                        !Objects.equals(sysUser.getSex(), Integer.parseInt(r.getXBM())) ||
                        !Objects.equals(sysUser.getPhone(), r.getFILED4()) ||
                        StringUtils.isBlank(sysUser.getWorkNo())) {
                    sysUser.setRealname(r.getXM());
                    sysUser.setSex(Integer.parseInt(r.getXBM()));
                    sysUser.setWorkNo(r.getXH());
                    if (sysUserService.updateById(sysUser)) {
                        log.info("用户更新成功：{}", r.getXH());
                    }
                    else {
                        log.info("用户更新失败：{}", r.getXH());
                    }
                }
                Student student = studentService.getByStdNo(r.getXH());
                if (student == null) {
                    student = new Student();
                    student.setUserId(sysUser.getId());
                    student.setStdNo(r.getXH());
                    student.setSex(Integer.parseInt(r.getXBM()));
                    try {
                        student.setEntranceTime(new SimpleDateFormat("yyyyMMdd").parse(r.getRXNY()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    student.setName(r.getXM());
                    student.setCollege(r.getDWMC());
                    student.setMajor(r.getZYMC());
                    student.setGrade(r.getSZNJ());
                    student.setClazz(r.getBJMC());
                    student.setIdCard(r.getSFZJH());
                    student.setPhone(r.getFILED4());
                    if (r.getZZMMMC() != null && politicalMap.containsKey(r.getZZMMMC())) {
                        String s = politicalMap.get(r.getZZMMMC());
                        student.setPoliticalStatus(s);
                    }
                    boolean save = studentService.save(student);
                    if (save) {
                        log.info("学生入库完成：{}", r.getXH());
                    }
                }
                else if (!Objects.equals(student.getName(), r.getXM()) ||
                        !Objects.equals(student.getCollege(), r.getDWMC()) ||
                        !Objects.equals(student.getMajor(), r.getZYMC()) ||
                        !Objects.equals(student.getIdCard(), r.getSFZJH()) ||
                        !Objects.equals(student.getPhone(), r.getFILED4()) ||
                        (student.getPoliticalStatus() == null && r.getZZMMMC() != null) ||
                        !Objects.equals(student.getGrade(), r.getSZNJ()) ||
                        !Objects.equals(student.getClazz(), r.getBJMC())) {
                    student.setName(r.getXM());
                    student.setCollege(r.getDWMC());
                    student.setMajor(r.getZYMC());
                    student.setGrade(r.getSZNJ());
                    student.setClazz(r.getBJMC());
                    if (student.getPoliticalStatus() == null && r.getZZMMMC() != null && politicalMap.containsKey(r.getZZMMMC())) {
                        String s = politicalMap.get(r.getZZMMMC());
                        student.setPoliticalStatus(s);
                    }
                    if (studentService.updateById(student)) {
                        log.info("学生更新成功：{}", r.getXH());
                    }
                    else {
                        log.info("学生更新失败：{}", r.getXH());
                    }
                }
            });
            count -= size;
        }
        log.info(" --- 拉取学生信息调度结束 --- ");
    }

}
